<?php
/**
  * 发邮件接口
  *
  * Example: mail.php?mailto=guoyu1268@qq.com&subject=test&content=testcontent&from=xiaohei@xiaohei.me&copyto=guoyu1268@gmail.com&bcc=guoyu1268@gmail.com
  */

include dirname(dirname(__FILE__)) . "/conf.php";

// 获取参数
$mailto = post_str('mailto');
$subject = post_str('subject');
$content = post_str('content');
$from = post_str('from');
$copyto = post_str('copyto');
$bcc = post_str('bcc'); // blind carbon copy

// 初始化返回值
$status = 'fail';
$error = '';

if ($mailto === false || $subject === false || $content === false){
    $error = 'parameters error';
    $result = array('status' => $status, 'error' => $error);
    echo json_encode($result);
    exit;
}

// mailto,subject,content
if (empty($subject) || empty($content)){
    $error = 'Mailto, Subject, Content not null';
    $result = array('status' => $status, 'error' => $error);
    echo json_encode($result);
	exit;
}

// mailto
$mailto = multi_mail($mailto);

// headers
$header_arr = array();
// from
if ($from !== false){
	if (!check_email($from)){
        $error = 'From mail error';
        $result = array('status' => $status, 'error' => $error);
	    exit;
	}
}else{
	$from = 'gouyu1268@qq.com';
}
$header_arr[] = 'From: ' . $from;
// copyto
if ($copyto !== false){
	$header_arr[] = 'Cc: ' . multi_mail($copyto);
}
// bcc
if ($bcc !== false){
	$header_arr[] = 'Bcc: ' . multi_mail($bcc);
}
$header = implode("\r\n", $header_arr);
// headers end

$content = str_replace("\n.", "\n..", $content);

mail($mailto, $subject, $content, $header);
mail_log(); // 发邮件日志
$status = 'succ';
$result = array('status' => $status, 'error' => $error);
echo json_encode($result);
exit;




// check multi mail
// 其中一个邮件地址出错，就会跳出页面
function multi_mail($mails){
	global $status, $error;
	$false_mail = array();
	$mail_arr = explode(',', $mails);
	foreach ($mail_arr as $key=>$mail){
		$mail = trim($mail);
		if (empty($mail_arr[$key])){
			unset($mail_arr[$key]);
			continue;
		}
		if (!check_email($mail)){
			$false_mail[] = $mail;
		}else{
			$mail_arr[$key] = $mail;
		}
	}
	if (count($false_mail) > 0){
		$error_str = 'Error mailto: [' . implode(', ', $false_mail) . ']';
        $error = $error_str;
        $result = array('status' => $status, 'error' => $error);
        echo json_encode($result);
        exit;
	}elseif(count($mail_arr) == 0){
        $error = 'No valid mailto';
        $result = array('status' => $status, 'error' => $error);
        echo json_encode($result);
        exit;
	}else{
		$mails = implode(', ', $mail_arr);
	}

	return $mails;
}

// 发邮件日志
function mail_log(){
	/*
	require_once('func/ip.php');

	$clientip = getclientip();
	if ($clientip){
		$ip_area = convertip($clientip);
	}else{
		$clientip = $ip_area = '';
	}
	$time = date('Y-m-d H:i:s');
	*/

	return true;
}
